import React, { PureComponent } from "react";
import { Card, Spin, Divider, Modal } from "antd";
import { connect } from "dva";
// import { Link } from "react-router-dom";
// import queryString from 'query-string';
import dynamic from "umi/dynamic";
import styles from "pages/flowimplement/flowexecution/index.less";
import PageLayout from "components/pageconlayout/PageLayout";
import { getMenuRouter, getPageOperate } from "components/layouts/menuFn";

import { openNotificationWithIcon, delay, getUuid } from "utils/comm";
// import DealForm from "pages/flowimplement/flowexecution/components/DealForm";

import SearchTable, {
  getTableProps,
} from "components/searchTable/SearchTable.jsx";

import CustomForm from "../../components/customForm/CustomForm";
/*
const TableList = dynamic(async () => {
  await delay(800);
  return import('components/tablelist/TableList');
});
const QueryExtra = dynamic(async () => {
  await delay(500);
  return import('pages/flowimplement/flowexecution/components/QueryExtra');
});
*/
const Catalogue = dynamic({
  loader: async () => {
    await delay(100);
    return import("components/catalogue/Catalogue");
  },
});
/*
const AdvancedFilter = dynamic(async () => {
  await delay(1000);
  return import('pages/flowimplement/flowexecution/components/AdvancedFilter');
});
*/

@connect(({ FlowExecution, appListMenu, loading, Public }) => ({
  FlowExecutionStore: FlowExecution,
  loading,
  menuAppStore: appListMenu,
  focusApp: appListMenu.focusApp,
  menuDataList: Public.menuDataList,
  resourceList: Public.resourceList,
}))
class FlowExecution extends PureComponent {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon;
    this.getMenuRouter = getMenuRouter.bind(this);
    this.getPageOperate = getPageOperate.bind(this);
    this.procDefKey = "";
    this.state = {
      page: {
        pageNum: 1,
        pageSize: 10,
      },
      filterVisible: false,
      visible: false,
      selectedKeys: [],
    };
    this.baseQueryParams = {
      appId: "",
      busiId: "",
      searchKey: "",
      timeStart: "", // 开始时间
      timeEnd: "", // 结束时间
    };
    this.queryParams = this.baseQueryParams;
    this.columns = [
      {
        title: "序号",
        dataIndex: "deploymentId",
        render: (value, record, index) => {
          const {
            page: { pageNum, pageSize },
          } = this.state;
          return (pageNum - 1) * pageSize + index + 1;
        },
      },
      {
        title: "流程名称",
        dataIndex: "procDefName",
        key: "procDefName",
      },
      {
        title: "流程编码",
        dataIndex: "procDefKey",
        key: "procDefKey",
      },
      {
        title: "版本",
        dataIndex: "version",
        key: "version",
        width: "12%",
      },
      /* {
      title: '所属应用',
      dataIndex: 'appName',
      key: 'appName',
    }, {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    }, {
      title: '创建人',
      dataIndex: 'creatorName',
      key: 'creatorName',
      width: '16%',
    }, */ {
        title: "操作",
        dataIndex: "opration",
        render: (text, record) => {
          const apply = this.getOprateDisable("apply");
          return (
            <div>
              {apply && (
                <a
                  onClick={(e) => {
                    e.preventDefault();
                    this.handleDealFormVisible(true, record, false);
                  }}
                >
                  发起申请
                </a>
              )}
              <Divider type="vertical" />
              <a
                href={`${window.location.origin}${
                  window.routerBase || "/"
                }flowmanage/flowconfigure/detail?deploymentId=${record.deploymentId}`}
                target="_blank"
                rel="noopener noreferrer"
              >
                详情
              </a>
            </div>
          );
        },
      },
    ];
  }

  componentDidMount() {
    this.isLeaf = false;
    this.initAppListData();
    this.initData();
  }

  componentDidUpdate(preProps) {
    const { focusApp } = this.props;
    const { focusApp: preFocusApp } = preProps;
    if (preFocusApp.id && `${preFocusApp.id || 0}` !== `${focusApp.id || 0}`) {
      // 应用切换更新页面数据
      this.initAppListData();
      this.resetPageData();
    }
  }

  componentWillUnmount() {
    this.isLeaf = true;
    const { dispatch } = this.props;
    dispatch({ type: "FlowExecution/clearData" });
  }

  // 加载应用数据
  initAppListData = () => {
    const { dispatch } = this.props;
    dispatch({ type: "appListMenu/getAppListData" });
  };


  // 重置页面数据
  resetPageData = () => {
    const { dispatch } = this.props;
    this.queryParams = this.baseQueryParam;
    dispatch({ type: "FlowExecution/clearData" });
    this.setState({
      page: { pageNum: 1, pageSize: 10 },
      filterVisible: false,
      selectedKeys: [],
    });
    if (this.QueryExtra) this.QueryExtra.handleReset();
    if (this.AdvancedFilter) this.AdvancedFilter.handleReset();
  };

  getOprateDisable = (type) => {
    const {
      location: { pathname = "" },
      menuDataList,
      resourceList,
    } = this.props;
    const res = this.getPageOperate(type, pathname, menuDataList, resourceList);
    return res;
  };

  // 获取查询参数
  getQueryParam = () => {
    const {
      page: { pageNum, pageSize },
    } = this.state;
    return { ...this.queryParams, pageNum, pageSize };
  };

  // 获取查询条件组件的this
  getRef = (type, _this) => {
    this[type] = _this;
  };

  // 查询条件改变
  handleParamsChange = (item = {}) => {
    this.queryParams = { ...this.queryParams, ...item };
  };

  // 触发查询
  initData = () => {
    const { dispatch } = this.props;
    const params = this.getQueryParam();
    // if (!params.appId && !params.busiId) return;
    dispatch({ type: "FlowExecution/getFlowListData", payload: params }).then(
      ({ errCode, errMsg }) => {
        if (errCode !== 0) {
          this.openNotificationWithIcon("error", "", errMsg || "获取数据失败");
        }
      },
    );
  };

  // 页码页数改变
  handlePageChange = (pageNum, pageSize) => {
    this.setState({ page: { pageNum, pageSize } }, () => {
      this.initData();
    });
  };

  // 搜索
  handleSearch = () => {
    const { page } = this.state;
    this.setState({ page: { ...page, pageNum: 1 } }, () => {
      this.initData();
    });
  };

  handleTreeNodeSelect = (data, e, preId, nomalSelectedKeys) => {
    const Keys = data[0].split("|");

    const newSelectkeys = nomalSelectedKeys || data;
    const queryParams = { ...this.queryParams };
    if (!(data && data[0].length > 0)) return;
    if (e.node.props.isLeaf) {
      // 子节点
      this.queryParams = {
        ...queryParams,
        busiId: data[0],
        appId: "",
        tenantId: "",
      };
    } else if (Keys[0] === "tenant") {
      this.queryParams = {
        ...queryParams,
        tenantId: Keys[Keys.length - 1],
        appId: "",
        busiId: "",
      };
    } else {
      this.queryParams = {
        ...queryParams,
        appId: Keys[Keys.length - 1],
        busiId: "",
        tenantId: "",
      };
    }
    this.setState({ selectedKeys: newSelectkeys });
    this.handleSearch();
  };

  // 部署

  handleDealFormVisible = (visible, record = "", isQuery = false) => {
    const { dispatch } = this.props;
    this.record = record;
    // this.setState({ visible });
    if (visible === true) {
      this.handleTaskForm(record, visible);
    } else {
      dispatch({ type: "FlowExecution/get/getForm", payload: [] });
      this.setState({ visible });
    }
    if (isQuery) {
      this.handleSearch();
    }
  };

  handleTaskForm = (record, visible) => {
    const { procDefKey } = record || {};
    this.procDefKey = procDefKey;
    const { dispatch } = this.props;
    dispatch({
      type: "FlowExecution/isExternalForm",
      payload: { processDefinitionKey: procDefKey },
    }).then(
      ({ errCode: _errCode, datas: _datas }) => {
        if (_errCode === 0 && _datas === true) {
          dispatch({
            type: "FlowExecution/startWithExternalForm",
            payload: { processDefinitionKey: procDefKey },
          }).then(({ errCode }) => {
            if (errCode === 0) {
              this.setState({ visible });
            }
          })
        } else {
          dispatch({
            type: "FlowExecution/getForm",
            payload: { processDefinitionKey: procDefKey },
          }).then(({ errCode, errMsg, datas }) => {
            if (errCode !== 0) {
              this.openNotificationWithIcon(
                "error",
                "",
                errMsg || "获取处理表单信息失败",
              );
            } else if (!datas || JSON.stringify(datas) === "{}") {
              Modal.confirm({
                title: "当前暂无表单，可点击确认直接申请",
                okText: "确认",
                cancelText: "取消",
                onOk: () => this.handleFormSave({}),
                onCancel: this.handleCancel,
              });
            } else {
              this.setState({ visible });
            }
          });
        }
      }
    )
  };

  // Apply = (record = {}) => {
  //   const { procDefKey } = record;
  //   if (!procDefKey) return;
  //   const { dispatch } = this.props;
  //   dispatch({ type: "FlowExecution/processStart", payload: { processDefinitionKey: procDefKey} }).then(({ errCode }) => {
  //     if (errCode === 0) {
  //       this.openNotificationWithIcon('success', '', '申请成功');
  //       this.handleSearch();
  //     }
  //   });
  // }

  handleFilterVisible = () => {
    const { filterVisible } = this.state;
    this.setState({ filterVisible: !filterVisible });
  };

  handleFormSave = (values) => {
    // console.log(values);
    const payload = {
      variables: values,
      processDefinitionKey: this.procDefKey,
    };
    const externalPayload = {
      formId: getUuid(),
      processDefinitionKey: this.procDefKey,
    };
    const { dispatch, FlowExecutionStore } = this.props;
    const { isExternalForm } = FlowExecutionStore;
    dispatch({
      type: "FlowExecution/processStart",
      payload: isExternalForm === true ? externalPayload : payload,
    }).then(({ errCode, errMsg }) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon("error", "", errMsg || "申请提交失败");
      } else {
        this.handleDealFormVisible(false);
        this.openNotificationWithIcon("success", "", "申请提交成功");
      }
    });
  };

  handleCancel = () => {
    this.handleDealFormVisible(false);
  };

  render() {
    const { FlowExecutionStore = {}, menuAppStore, loading } = this.props;
    const {
      page: { pageNum, pageSize },
      /* filterVisible, */ visible,
      selectedKeys,
    } = this.state;
    const {
      flowListData = [],
      totalCount = 0,
      taskformFields = [],
      formUrl = "",
      isExternalForm,
    } = FlowExecutionStore;

    const { appListMenuData = [] } = menuAppStore;
    const listLoading =
      loading.effects["FlowExecution/getFlowListData"] || false;
    const startLoading = loading.effects["FlowExecution/processStart"] || false;
    const formLoading = loading.effects["FlowExecution/getForm"] || false;

    const menuListLoading =
      loading.effects["appListMenu/getAppListData"] || false;
    return (
      <div className={styles.root}>
        <PageLayout
          leftContent={
            <Card
              // title='应用业务目录'
              title="目录"
              style={{
                width: "100%",
                height: "100%",
                minHeight: window.innerHeight - 64 - 16 - 16 - 104,
              }}
            >
              <Spin spinning={menuListLoading} delay={300}>
                <Catalogue
                  CatalogueData={appListMenuData}
                  treeNodeSelect={this.handleTreeNodeSelect}
                  selectedKeys={selectedKeys}
                />
              </Spin>
            </Card>
          }
          rightContent={
            <Spin spinning={false} delay={300}>
              <Card
                title={
                  <span className="list__title">{`流程列表（${totalCount}）`}</span>
                }
                /*
                extra={
                  <QueryExtra
                    onChange={this.handleParamsChange}
                    onSearch={this.handleSearch}
                    visible={filterVisible}
                    handleFilterVisible={this.handleFilterVisible}
                    getRef={(_this) => this.getRef('QueryExtra', _this)}
                  />
                }
                */
                bodyStyle={{
                  minHeight: window.innerHeight - 64 - 16 - 16 - 48 - 104,
                }}
                style={{ width: "100%" }}
              >
                {/*
                <AdvancedFilter
                  handleSearch={this.handleSearch}
                  handleParamsChange={this.handleParamsChange}
                  visible={filterVisible}
                  getRef={(_this) => this.getRef('AdvancedFilter', _this)}
                />
                <TableList
                  dataSource={flowListData}
                  loading={listLoading}
                  columns={this.columns}
                  titleName='procDefName'
                  operationName='opration'
                  onPageChange={this.handlePageChange}
                  rowKey='procDefId'
                  className={styles.listcon}
                  pagination={{
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: ['6', '10', '20', '30'],
                    current: pageNum,
                    pageSize,
                    total: totalCount,
                  }}
                />
                */}
                <SearchTable
                  showHeader={false}
                  tableProps={getTableProps({
                    rowKey: "deploymentId",
                    columns: this.columns,
                    dataSource: flowListData,
                    loading: listLoading || formLoading,
                    pagination: {
                      current: pageNum,
                      pageSize,
                      total: totalCount,
                      onChange: this.handlePageChange,
                      onShowSizeChange: this.handlePageChange,
                    },
                  })}
                />
              </Card>
            </Spin>
          }
        />
        {visible && (
          <CustomForm
            title="发起申请"
            visible={visible}
            confirmLoading={startLoading}
            onOk={(values) => {
              this.handleFormSave(values);
            }}
            onCancel={this.handleCancel}
            formConfigData={taskformFields}
            formUrl={formUrl}
            isExternalForm={isExternalForm}
            dataLoading={formLoading}
            emptyWord="当前无表单，可直接申请"
            action="申请"
          />
        )}
        {/* {visible && (
          <DealForm
            visible={visible}
            handleCancel={this.handleDealFormVisible}
            dispatch={dispatch}
            // data={this.record || {}}
            disable={this.disable}
            procDefKey={(this.record || {}).procDefKey || ""}
            confirmLoading={startLoading}
          />
        )} */}
      </div>
    );
  }
}

export default FlowExecution;
